package com.leezai.mqtt.utils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class FieldCopyUtils {

    /**
     * 生成字段映射代码
     * @param sourceClazz
     * @param targetClazz
     */
    public void test(Class<?> sourceClazz,Class<?> targetClazz) {
        // 获取两个类的字段
        Field[] sourceFields = sourceClazz.getDeclaredFields();
        Field[] targetFields = targetClazz.getDeclaredFields();

        System.out.println("public " + targetClazz.getSimpleName() + " map" + sourceClazz.getSimpleName() + "To" + targetClazz.getSimpleName()
                + "(" + sourceClazz.getSimpleName() + " source) {");
        System.out.println("    if (source == null) return null;");
        System.out.println("    " + targetClazz.getSimpleName() + " target = new " + targetClazz.getSimpleName() + "();");
        System.out.println("");

        // 创建目标字段映射，便于查找
        Map<String, Field> targetFieldMap = new HashMap<>();
        for (Field field : targetFields) {
            targetFieldMap.put(field.getName(), field);
        }

        // 生成映射代码
        for (Field sourceField : sourceFields) {
            String fieldName = sourceField.getName();
            Class<?> fieldType = sourceField.getType();

            // 检查目标类中是否存在同名字段
            if (targetFieldMap.containsKey(fieldName)) {
                Field targetField = targetFieldMap.get(fieldName);
                // 检查字段类型是否兼容
                if (targetField.getType().equals(fieldType)) {
                    System.out.println("    target.set" + capitalize(fieldName) + "(source.get" + capitalize(fieldName) + "());");
                } else {
                    System.out.println("    // TODO: 需要类型转换 " + fieldName + " from " + fieldType.getSimpleName() + " to " + targetField.getType().getSimpleName());
                }
            }
        }

        System.out.println("");
        System.out.println("    return target;");
        System.out.println("}");
    }

    private String capitalize(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }
}
